package org.vsg.common.pagination.web.taglibs.html;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.vsg.common.pagination.Pagination;
import org.vsg.common.pagination.web.taglibs.PaginationBarTag;

public class PageIndexItemTag extends BaseStyleTag {
	
	private String contentStyle;
	
	public PageIndexItemTag() {
		contentStyle = readStyle();		
	}
	
	

	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();

		Pagination pagination = null;
	
		// find the parent tag
		PaginationBarTag parent = (PaginationBarTag)findAncestorWithClass(this,PaginationBarTag.class);
		if (parent == null) {
			throw new JspException("�˱�ǲ��ڸ����\"SimplePaginationBarTag\"��!");
		} else {
			pagination = parent.getPagination();
		}
		
		// parse variabe for current page
		String currentPage = "0";
		if (pagination.getPageIndex() == 0 && pagination.getTotalRecord() == 0) {

		} else {
			currentPage = Integer.toString(pagination.getPageIndex()+1);			
		}
		
		String totalPage = Integer.toString(pagination.getTotalPages());
		
		contentStyle = contentStyle.replaceAll("\\$\\{currentPage\\}",currentPage);
		contentStyle = contentStyle.replaceAll("\\$\\{totalPage\\}",totalPage);

		JspWriter writer = pageContext.getOut();
		try {
			writer.write(contentStyle.toString());			
		} catch (IOException ioe) {
			ioe.printStackTrace();			
		}		
		
		return SKIP_BODY;
	}
	
	
	private String readStyle() {
		// read file upload resources file
		StringBuffer styleContent = new StringBuffer();
		try {
			InputStream inputStream = getClass().getResourceAsStream("currentpageitem.style");
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String line = null;
			
			while ( (line = bufferedReader.readLine()) != null)  {
				styleContent.append(line).append("\n");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return styleContent.toString();
	}	
	
	
	
}
